package com.vpen.picupload.aspect;

import com.vpen.picupload.annotation.History;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Arrays;


/**
 * -@Version 1.0
 * -@Author:Vpen
 * -@Date:2021/8/3 23:06
 * -@Content:
 */
@Component
@Aspect
@Slf4j
public class OperationAspect {
    /**
     * 作者:韦鹏
     * 描述: 定义切入点
     * */
    @Pointcut("@annotation(com.vpen.picupload.annotation.History)")
    public void pointcut(){}
    /**
     * 方法需要执行，才有返回值===@Around优先级高，需要它来执行
     */
    @AfterReturning(value = "pointcut()",returning = "result")
    public Object getResult(JoinPoint point,Object result){
        log.info("返回结果>>>{}",result);
        System.out.println("helloWorld");
        return null;
    }

    @Around("pointcut()")
    public Object operation(ProceedingJoinPoint pjp) throws Throwable {
        // 获取参数列表的值
        HttpServletRequest request=null;
        Object[] args = pjp.getArgs();
        for (Object a: args) {
            log.info("参数==>{}",a.toString());
            if (a instanceof HttpServletRequest) {
               request = (HttpServletRequest) a;
            }
        }
        // 强转参数数上的HttpServletRequest
        assert request != null;
        String uri = request.getRequestURI();
        log.info("URI====>{}",uri);

        // 获取注解
       MethodSignature ms= ((MethodSignature) pjp.getSignature());
        History history = ms.getMethod().getAnnotation(History.class);
        int i = history.operation();
        String username = history.username();
        log.info("注解标注的值操作类型==>{} 用户名==>{}",i,username);

        // 获取返回的Class对象
        Class returnType = ms.getReturnType();
        String name = returnType.getName();
        log.info("name==>{}",name);
        Constructor[] constructors = returnType.getConstructors();
        log.info("{}", Arrays.asList(constructors));

        Method msMethod = ms.getMethod();
        // 获取方法名
        String name1 = msMethod.getName();
        log.info(name1);
        Object value = msMethod.getDefaultValue();
        log.info("{}",value);
        // 获取参数
        Parameter[] parameters = msMethod.getParameters();
        for (Parameter p : parameters) {
            System.out.println(p);
        }
        log.info("{}", Arrays.asList(parameters));

        // 执行方法获取返回对象
        Object proceed = pjp.proceed();
        log.info("返回的结果===>{}",proceed);
        return null;
    }

}
